package com.jeeplus.test.jlnu.admissionInfo.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.jeeplus.test.jlnu.admissionInfo.domain.entity.AdmissionInfo;
import com.jeeplus.test.jlnu.admissionInfo.domain.entity.StudentInfoEntity;
import com.jeeplus.test.jlnu.admissionInfo.service.AdmissionExcelService;
import com.jeeplus.test.jlnu.admissionInfo.service.ExcelServiceStu;

import java.util.ArrayList;
import java.util.List;

public class AdmissionDataListener extends AnalysisEventListener<AdmissionInfo> {

    private final AdmissionExcelService excelServiceStu;
    private final AdmissionDataListener.ProgressCallback progressCallback;
    private static final int BATCH_COUNT = 500;

    private List<AdmissionInfo> dataList = new ArrayList<>();
    private int totalRecords;
    private int currentRecords;

    public AdmissionDataListener(AdmissionExcelService excelServiceStu, AdmissionDataListener.ProgressCallback progressCallback, int totalRecords) {
        this.excelServiceStu = excelServiceStu;
        this.progressCallback = progressCallback;
        this.totalRecords = totalRecords;
    }

    @Override
    public void invoke(AdmissionInfo data, AnalysisContext context) {
        dataList.add(data);
        currentRecords++;

        if (dataList.size() >= BATCH_COUNT) {
            saveDataToDatabase();
            dataList.clear();
        }

        updateProgress();
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (!dataList.isEmpty()) {
            saveDataToDatabase();
            dataList.clear();
        }
        updateProgress();
    }

    private void saveDataToDatabase() {
        if (!dataList.isEmpty()) {
            excelServiceStu.insertDataAdmission(dataList);
        }
    }

    private void updateProgress() {
        int progress = (int) (((double) currentRecords / totalRecords) * 100);
        progressCallback.onProgress(progress);
    }

    public interface ProgressCallback {
        void onProgress(int progress);
    }
}
